<?php
namespace App\Admin\Actions\Import\StaffImport;

use App\Actions\DepartmentFileUploadAction;
use App\Models\AdminUser;
use App\Models\Department;
use App\Models\DepartmentFile;
use App\Policies\Admin\UploadPolicy;
use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Contracts\LazyRenderable;

class ImportPDFForm extends Form implements LazyRenderable
{
    use LazyWidget;

    // 处理请求
    public function handle(array $input)
    {
        $admin_user = AdminUser::find(Admin::user()->id);
        $dwdm = $input['dwdm'];
        $upload_type = $input['upload_type'];
        
        $department = Department::findByDwdm($dwdm);
        if (!$department) {
            return $this->response()->error('单位不存在');
        }
        if (!UploadPolicy::make($department, $admin_user)->can_upload()) {
            return $this->response()->error('没有权限上传');
        }

        if (!$input['files']) {
            return $this->response()->error('请上传文件');
        }
        if (count($input['files']) == 0) {
            return $this->response()->error('请至少上传一个文件');
        }
        try {
            if ($upload_type == 'fushu') {
                DepartmentFileUploadAction::make($department, $admin_user)->uploadFuShu($input['files'], $department);
            } else {
                DepartmentFileUploadAction::make($department, $admin_user)->uploadStaff($input['files'], $department);
            }
            return $this->response()->success('导入成功')->refresh();
        } catch (\Throwable $th) {
            $error_messages = '<div style="text-align: left; max-height: 500px; overflow-y: scroll">'.$th->getMessage().'</div>';
            return $this->response()->script("
            Dcat.swal.fire({
                title: '导入结果提醒',
                html: '{$error_messages}',
                heightAuto: false,
                showCancelButton: false,
                confirmButtonText: '关闭',
                allowOutsideClick: false,
            }).then((result) => {
                if (result.value) {
                    Dcat.reload()
                } else {
                    Dcat.reload()
                }
            })");
        }
    }

    public function form()
    {  
        $dwdm = $this->payload['dwdm'] ? $this->payload['dwdm'] : '';
        $upload_type = $this->payload['upload_type'] ? $this->payload['upload_type'] : '';

        if ($dwdm) {
            $this->multipleFile('files', '文件')->url(admin_route('files.upload'))->autoUpload()->autoSave(false)->accept('pdf')->maxSize(10*1024)
                ->help('允许上传多个文件，只允许上传pdf文件，单个文件大小不超过10M，重新上传将会覆盖同名的文件。');
        }
        $this->hidden('dwdm')->value($dwdm);
        $this->hidden('upload_type')->value($upload_type);
        $this->disableResetButton();
    }
}